﻿import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15

Item {
    id: root

    // ========== 公共API ==========

    // 属性
    property alias model: listView.model
    property bool singleSelectionMode: true
    property int itemHeight: 50
    property color normalColor: "white"
    property color hoverColor: "#F5F5F5"
    property color selectedColor: "#4CAF50"
    property color selectedHoverColor: "#43A047"
    property color textColor: "black"
    property color selectedTextColor: "white"
    property string displayRole: "name"
    property bool showStatusBar: true
    property real diameter: 15

    // 信号
    signal itemSelected(int index, bool selected)
    signal selectionChanged(var selectedIndices)
    signal rightClicked(var mouse)  // 修改为传递鼠标事件

    // 方法
    function clearSelection() {
        internal.clearAllSelections()
    }

    function selectAll() {
        internal.selectAllItems()
    }

    function getSelectedIndices() {
        return internal.getSelectedItems(true)
    }

    function getSelectedItems() {
        return internal.getSelectedItems(false)
    }

    function addItem(itemData) {
        internal.addItemToList(itemData)
    }

    // ========== 内部实现 ==========

    QtObject {
        id: internal

        property string selectionRole: "selected"

        function clearAllSelections() {
            for (var i = 0; i < listView.model.count; i++) {
                if (listView.model.get(i)[internal.selectionRole]) {
                    listView.model.setProperty(i, internal.selectionRole, false)
                }
            }
            root.selectionChanged([])
            statusAnimation.start()
        }

        function selectAllItems() {
            for (var i = 0; i < listView.model.count; i++) {
                if (!listView.model.get(i)[internal.selectionRole]) {
                    listView.model.setProperty(i, internal.selectionRole, true)
                }
            }
            root.selectionChanged(internal.getSelectedItems(true))
            statusAnimation.start()
        }

        function getSelectedItems(returnIndices) {
            var result = []
            for (var i = 0; i < listView.model.count; i++) {
                var item = listView.model.get(i)
                if (item[internal.selectionRole]) {
                    if (returnIndices) {
                        result.push(i)
                    } else {
                        result.push(item)
                    }
                }
            }
            return result
        }

        function addItemToList(itemData) {
            if (!itemData.hasOwnProperty(internal.selectionRole)) {
                itemData[internal.selectionRole] = false
            }
            listView.model.append(itemData)
        }

        function handleLeftClick(index) {
            var item = listView.model.get(index)
            var newSelectedState = !item[internal.selectionRole]

            if (root.singleSelectionMode) {
                // 单选模式 - 取消之前的选择
                for (var i = 0; i < listView.model.count; i++) {
                    if (i !== index && listView.model.get(i)[internal.selectionRole]) {
                        listView.model.setProperty(i, internal.selectionRole, false)
                        root.itemSelected(i, false)
                    }
                }
            }

            listView.model.setProperty(index, internal.selectionRole, newSelectedState)
            root.itemSelected(index, newSelectedState)
            root.selectionChanged(internal.getSelectedItems(true))
            statusAnimation.start()
        }
    }

    // ========== 可视化部分 ==========

    Column {
        anchors.fill: parent
        spacing: 2

        // 列表视图外层的鼠标区域，用于捕获整个列表区域的右键点击
        MouseArea {
            id: listContainerArea
            width: parent.width
            height: showStatusBar ? parent.height - 40 : parent.height
            acceptedButtons: Qt.RightButton

            onClicked: (mouse) => {
                root.rightClicked(mouse)
                contextMenu.popup()
            }

            ListView {
                id: listView
                width: parent.width
                height: parent.height
                clip: true
                spacing: 2

                delegate: Rectangle {
                    id: delegateItem
                    width: listView.width
                    height: root.itemHeight

                    // 动态计算背景色
                    color: {
                        if (model[internal.selectionRole]) {
                            return itemMouseArea.containsMouse ? root.selectedHoverColor : root.selectedColor
                        } else {
                            return itemMouseArea.containsMouse ? root.hoverColor : root.normalColor
                        }
                    }

                    border.color: "#CCCCCC"
                    radius: 4

                    // 背景色变化动画
                    Behavior on color {
                        ColorAnimation { duration: 200 }
                    }

                    // 按下时的缩放效果
                    scale: itemMouseArea.pressed ? 0.98 : 1.0
                    Behavior on scale {
                        NumberAnimation { duration: 100 }
                    }

                    // 内容文本
                    Text {
                        anchors {
                            verticalCenter: parent.verticalCenter
                            left: parent.left
                            leftMargin: 15
                        }
                        text: model[root.displayRole] || ""
                        font.pixelSize: 16
                        color: model[internal.selectionRole] ? root.selectedTextColor : root.textColor

                        Behavior on color {
                            ColorAnimation { duration: 200 }
                        }
                    }

                    // 选中指示器
                    Rectangle {
                        id: checkIndicator
                        visible: model[internal.selectionRole]
                        anchors {
                            right: parent.right
                            rightMargin: 15
                            verticalCenter: parent.verticalCenter
                        }
                        width: root.diameter // 20
                        height: root.diameter // 20
                        radius: 10
                        color: "white"
                        opacity: model[internal.selectionRole] ? 1.0 : 0.0
                        scale: model[internal.selectionRole] ? 1.0 : 0.5

                        Behavior on opacity {
                            NumberAnimation { duration: 200 }
                        }
                        Behavior on scale {
                            NumberAnimation {
                                duration: 300
                                easing.type: Easing.OutBack
                            }
                        }

                        Text {
                            anchors.centerIn: parent
                            text: "✓"
                            color: root.selectedColor
                            font.bold: true
                        }
                    }

                    // 列表项的鼠标区域（只处理左键）
                    MouseArea {
                        id: itemMouseArea
                        anchors.fill: parent
                        hoverEnabled: true
                        acceptedButtons: Qt.LeftButton  // 只响应左键

                        onClicked: (mouse) => {
                            if (mouse.button === Qt.LeftButton) {
                                internal.handleLeftClick(index)
                            }
                        }
                    }
                }
            }
        }

        // 状态栏
        Rectangle {
            id: statusBar
            width: parent.width
            height: 40
            visible: showStatusBar
            color: "#EEEEEE"

            Text {
                id: statusText
                anchors.centerIn: parent
                text: {
                    var count = internal.getSelectedItems(true).length
                    return "已选择: " + count + " 项" +
                           (root.singleSelectionMode ? " (单选模式)" : " (多选模式)")
                }
                font.bold: true
            }

            Behavior on color {
                ColorAnimation { duration: 300 }
            }
        }
    }

    // 右键菜单
    Menu {
        id: contextMenu

        MenuItem {
            text: "清除选择"
            onTriggered: root.clearSelection()
        }

        MenuItem {
            text: "全部选择"
            onTriggered: root.selectAll()
        }
    }

    // 状态栏动画
    SequentialAnimation {
        id: statusAnimation
        PropertyAnimation {
            target: statusBar
            property: "color"
            to: "#E3F2FD"
            duration: 200
        }
        PropertyAnimation {
            target: statusBar
            property: "color"
            to: "#EEEEEE"
            duration: 300
        }
    }

    // 点击菜单外部关闭菜单
    MouseArea {
        anchors.fill: parent
        enabled: contextMenu.visible
        onClicked: contextMenu.close()
        z: -1  // 确保在菜单下方
    }
}
